package leetcode.problems.P19删除链表的倒数第N个结点;

public class RemoveNthFromEnd {
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

// 快慢指针
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1, head);
        ListNode lastNPrev = dummy, cur = dummy;
        for (int i = 0; i < n; ++i) {
            cur = cur.next;
        }
        while (cur.next != null) {
            cur = cur.next;
            lastNPrev = lastNPrev.next;
        }
        lastNPrev.next = lastNPrev.next.next;
        return dummy.next;
    }
}